package com.kitty.game.gm;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespUpdate;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fuling.FulingController;
import com.kitty.game.fuling.model.Fuling;
import com.kitty.game.gm.handler.GMFather;
import com.kitty.game.gm.handler100.NCGmFather;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.role.model.Account;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.AccountService;
import com.kitty.game.utils.PrivilegeConst;
import com.kitty.mina.message.Message;
import com.kitty.mina.message.MessagePusher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;

@Component
public class GmDispatcher {
    Logger logger = LoggerFactory.getLogger(GmDispatcher.class);
    @Autowired
    @Qualifier("gameConversion")
    ConversionService conversionService;
    @Autowired
    GmCommandHandler commandHandler;
    @Autowired
    AccountService accountService;
    @Autowired
    protected PetService petService;

    static String[] zhenlingType = new String[] { "青龙", "白虎", "朱雀", "玄武" };


    public boolean dispatch(Role player, String command) {
        logger.info("command:验证账号权限"+command);
        /**验证账号权限*/
        Account account = accountService.getAccount(player.getSid());
        if (command.startsWith("@@@")) {
            return dispatchOther200(player, command);
        }
        if (command.startsWith("@@")) {
            return dispatchOther1000(player, command);
        }//gm权限的等级
        if (SpringUtils.getBean(ServerService.class).getNeice() != 100 && account.getPrivilege() != PrivilegeConst.admin) {
            return false;
        }
        return dispatchOther100(player, command);
    }

    private boolean dispatchOther100(Role player, String command) {
        logger.info("command:"+command);
        String[] args = command.split("=");
        logger.info("args:"+args);
        String gmParams = args[0];
        if(args.length>2){
            int i = command.indexOf("=");
            if(i>=0){
                args[1] = command.substring(i+1);
            }
        }
//        if (!gmParams.startsWith("@")) {
//            return false;
//        }
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("未鉴定","@zhuangbei");
        hashMap.put("首饰X5","@shoushiX5");
        hashMap.put("首饰","@shoushi");
        hashMap.put("装备","@equip");
        hashMap.put("帮贡","@banggong");
        hashMap.put("阴德","@yinde");
        hashMap.put("抽奖","@choujiang");
        hashMap.put("积分","@jifen");
        hashMap.put("奇门积分","@qimen");
        hashMap.put("好心值","@haoxin");
        hashMap.put("元宝","@gold");
        hashMap.put("武学","@matiral");
        hashMap.put("潜能","@qianneng");
        hashMap.put("宠物","@pet");
        hashMap.put("金币","@jinbi");
        hashMap.put("充值","@chongzhi");
        hashMap.put("法宝","@fabao");
        hashMap.put("经验","@exp");
        hashMap.put("道行","@daohang");
        hashMap.put("属性","@shuxin");
        hashMap.put("物品","@wupin");
        gmParams = gmParams.substring(0);
        if(!hashMap.containsKey(gmParams)){
            return false;
        }
        gmParams = hashMap.get(gmParams);
        GmService gmService = SpringUtils.getBean(GmService.class);
        NCGmFather gmFather = gmService.getGm100().get(gmParams);
        if (gmFather != null){
            gmFather.handle(player,args[1].trim());
            return true;
        }
//        gmParams = gmParams.substring(1);
//
//        gmParams = hashMap.get(gmParams);
//        for (Method method : GmCommandHandler100.class.getDeclaredMethods()) {
//            if (gmParams.equalsIgnoreCase(method.getName())) {
//                try {
//                    // 动态参数要求只能有两个参数，第二个需要是 String[] 类型
//                    String content = args[1];
//                    Object[] methodParams = new Object[2];
//                    methodParams[0] = player;
//                    methodParams[1] = conversionService.convert(args[1], method.getParameterTypes()[1]);
//                    method.invoke(SpringUtils.getBean(GmCommandHandler100.class), methodParams);
//                    MessagePusher.pushMessage(player, new RespNotifyMiscEx("发送成功！"));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    MessagePusher.pushMessage(player, new RespNotifyMiscEx("命令错误！"));
//                }
//                break;
//            }
//        }
        return true;
    }


    private boolean isDynamicParams(Method method) {
        int paramSum = method.getParameterCount();
        if (paramSum <= 1) {
            return false;
        }
        return method.getParameterTypes()[paramSum - 1].isArray();
    }

    public boolean dispatchOther200(Role player, String command) {
        Account account = accountService.getAccount(player.getSid());
        if (account.getPrivilege() < PrivilegeConst.GM) {
            return false;
        }
        String[] args = command.split("==");
        String gmParams = args[0];
        if (!gmParams.startsWith("@@@")) {
            return false;
        }
        if (args.length != 2) {
            return false;
        }
        GMFather father = SpringUtils.getBean(GmService.class).getGm200().get(args[0]);
        if (father != null){
            return father.handle(player,args[1]);
        }
        gmParams = gmParams.substring(3);
        String roleName = args[1];
        for (Method method : GmCommandHandler200.class.getDeclaredMethods()) {
            if (gmParams.equalsIgnoreCase(method.getName())) {
                try {
                    Object[] methodParams = new Object[2];
                    methodParams[0] = player;
                    methodParams[1] = conversionService.convert(roleName, method.getParameterTypes()[1]);
                    method.invoke(SpringUtils.getBean(GmCommandHandler200.class), methodParams);
                    logger.error("admin=admin=={}={}={}={}={}={}", method.getName(), player.getName(), player.getUid(), player.getId(), methodParams[1]);
                    MessagePusher.pushMessage(player, new RespNotifyMiscEx("发送成功！"));
                } catch (Exception e) {
                    e.printStackTrace();
                    MessagePusher.pushMessage(player, new RespNotifyMiscEx("命令错误！"));
                }
                break;
            }
        }
        return true;
    }


    public boolean dispatchOther1000(Role player, String command) {
        /**验证账号权限*/
        Account account = accountService.getAccount(player.getSid());
        if (account.getPrivilege() != PrivilegeConst.admin) {
            return false;
        }
        String[] args = command.split("==");
        String gmParams = args[0];
        if (!gmParams.startsWith("@@")) {
            return false;
        }
        if (args.length != 3) {
            return false;
        }

        gmParams = gmParams.substring(2);
        String roleName = args[1];
        roleName = SpringUtils.getBean(GmService.class).replaceName(roleName);
        long targetUid = SpringUtils.getPlayerService().getUidBy(roleName);
        Role role = SpringUtils.getPlayerService().getPlayerBy(targetUid);
        if (role == null) {
            MessagePusher.pushMessage(player, new RespNotifyMiscEx("角色不存在"));
            return true;
        }
        for (Method method : GmCommandHandler.class.getDeclaredMethods()) {
            if (gmParams.equalsIgnoreCase(method.getName())) {
                try {
                    // 动态参数要求只能有两个参数，第二个需要是 String[] 类型
                    if (isDynamicParams(method)) {
                        String[] dynParams = new String[args.length - 1];
                        for (int i = 0; i < dynParams.length; i++) {
                            dynParams[i] = args[i + 1];
                        }
                        method.invoke(commandHandler, role, dynParams);
                    } else {
                        Object[] methodParams = new Object[2];
                        methodParams[0] = role;
                        methodParams[1] = conversionService.convert(args[2], method.getParameterTypes()[1]);
                        method.invoke(SpringUtils.getBean(GmCommandHandler.class), methodParams);
                        logger.error("admin=admin=={}={}={}={}={}={}", method.getName(), player.getName(), player.getUid(), player.getId(), methodParams[1]);
                    }
                    MessagePusher.pushMessage(player, new RespNotifyMiscEx("发送成功！"));
                } catch (Exception e) {
                    MessagePusher.pushMessage(player, new RespNotifyMiscEx("命令错误！"));
                    logger.error("",e);
                }
                break;
            }
        }
        return true;
    }
    public boolean dispatchPetFushen(Role role, String command) {
        Fuling fuling = SpringUtils.getFulingService().getFulingdata(role.getRoleId());
        if (fuling.getFushen2_id().equals("null"))
            return false;
        ArrayList<FiedValue> list = new ArrayList<>();
        command = command.substring(2);
        String typeName = zhenlingType[fuling.getType2() - 1];
        if (command.equals("解除宠物附身")) {
            fuling.setType2((byte)0);
            Pet pet = role.getPetBox().getPetByPetId(Integer.parseInt(fuling.getFushen2_id()));
            fuling.setFushen2_id("null");
            RespUpdate respUpdatePet = new RespUpdate();
            respUpdatePet.setRoleId(pet.getId());
            pet.setQinglong(1.0);
            pet.setBaihu(1.0);
            pet.setZhuque(1.0);
            pet.setXuanwu(1.0);
            String msg1 = MessageFormat.format("你成功取消了#R{0}真灵对#R宠物#n的附身。", new Object[] { typeName });
            list.add(new FiedValue(1005, Integer.valueOf(0)));
            pet.setZhenlingType((byte)0);
            respUpdatePet.setList(list);
            if (fuling.getFushen1_id().equals("null"))
                fuling.setType4((byte)0);
            this.petService.refreshPetInfo(role, pet);
            MessagePusher.pushMessage(role, (Message)new RespNotifyMiscEx(msg1));
            fuling.save();
            MessagePusher.pushMessage(role, (Message)respUpdatePet);
            MessagePusher.pushMessage(role, (Message)FulingController.getRespReqFuling(fuling));
        }
        return true;
    }

}